package com.zhang.flink.window;

import com.zhang.flink.bean.ClickEvent;
import com.zhang.flink.bean.UrlViewCountWindow;
import com.zhang.flink.example.source.ClickSource;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

/**
 * 每隔5s输出url访问次数
 *
 * @title: 使用底层API实现滚动窗口
 * @author: zhang
 * @date: 2022/2/13 23:41
 */
public class TumblingWindowWithKeyProcessFunction {
    public static void main(String[] args) throws Exception {
        //todo 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.url)
                .process(new UrlViewCountFunc())
                .print();

        env.execute();
    }

    public static class UrlViewCountFunc extends KeyedProcessFunction<String, ClickEvent, UrlViewCountWindow> {
        // key： 窗口开始时间
        //value：属于窗口的所有事件
        private MapState<Long, List<ClickEvent>> mapState;

        //窗口大小
        private Long windowSize = 5000L;

        @Override
        public void open(Configuration parameters) throws Exception {
            mapState = getRuntimeContext().getMapState(
                    new MapStateDescriptor<Long, List<ClickEvent>>(
                            "map-state",
                            Types.LONG, Types.LIST(Types.POJO(ClickEvent.class))
                    )
            );
        }

        @Override
        public void processElement(ClickEvent value, KeyedProcessFunction<String, ClickEvent, UrlViewCountWindow>.Context ctx, Collector<UrlViewCountWindow> out) throws Exception {
            //计算窗口
            long currTs = ctx.timerService().currentProcessingTime();
            long windowStartTime = currTs - currTs % windowSize;
            long windowEndTime = windowStartTime + windowSize;
            if (!mapState.contains(windowStartTime)) {
                ArrayList<ClickEvent> events = new ArrayList<>();
                events.add(value);
                mapState.put(windowStartTime, events);
            } else {
                mapState.get(windowStartTime).add(value);
            }

            ctx.timerService().registerProcessingTimeTimer(windowEndTime - 1L);
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<String, ClickEvent, UrlViewCountWindow>.OnTimerContext ctx, Collector<UrlViewCountWindow> out) throws Exception {

            long windowEndTime = timestamp + 1L;
            long windowStartTime = windowEndTime - windowSize;
            String url = ctx.getCurrentKey();
            long count = mapState.get(windowStartTime).size();
            out.collect(new UrlViewCountWindow(
                    url,
                    count,
                    windowStartTime,
                    windowEndTime
            ));
            mapState.remove(windowStartTime);
        }
    }
}
